import React, { useEffect, useState } from 'react';
import { Button, Drawer, Form, Select, Input } from 'antd';
import wrapper from '@utils/wrapper';
import { APIRecord } from '../';
import api from '@request/api_import';
import {apiTypes} from '../../mock';

interface CreateApiModalProps {
  type: 'add' | 'edit' | 'view',
  record: APIRecord,
  visible: boolean,
  closeDialog: () => void,
  getList: () => void
}
const actionType = {
  add: '新建',
  edit: '编辑',
  view: '查看'
}
const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
}
interface FormFieldsValue {
  name: string,
  access_type: string,
  type: string,
  desc: string,
  method?: string,
  url?: string,
  model_name?: string,
  endpoint?: string,
  token?: string
}
interface AddAPIParams {
  access_type: string,
  name: string,
  request_info: {
    method?: string,
    url?: string,
    model_name?: string,
    endpoint?: string,
    token?: string
  },
  type: string,
  version: string,
  desc?: string,
  id?: number,
  serverType?: string,
}
const Option = Select.Option;
const CreateApiModal = (props: CreateApiModalProps) => {
  const {
    type,
    record,
    visible,
    getList,
    closeDialog
  } = props;
  const [mode, setMode] = useState<string>('EAS');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { getFieldValue, validateFields, setFieldsValue } = form;
  const disabled = type === 'view' ? true : false;
  useEffect(() => {
    if (['view', 'edit'].includes(type)) {
      let setFieldsValues: FormFieldsValue = {
        name: record.name,
        access_type: record.access_type,
        type: record.type,
        desc: record.desc,
      }
      if (record.access_type === 'HTTP') {
        setFieldsValues = {
          ...setFieldsValues,
          method: record.request_info.method,
          url: record.request_info.url
        }
      } else {
        setFieldsValues = {
          ...setFieldsValues,
          endpoint: record.request_info.endpoint,
          model_name: record.request_info.model_name,
          token: record.request_info.token
        }
      }
      setFieldsValue({
        ...setFieldsValues
      })
      setMode(record.access_type);
    }
  }, [])
  const onOk = () => {
    if(type === 'view') return closeDialog && closeDialog();
    validateFields()
      .then(async (info: FormFieldsValue) => {
        let params: AddAPIParams = {
          name: info.name,
          access_type: info.access_type,
          desc: info.desc,
          type: info.type,
          request_info: {},
          version: '1.0.0',
        }
        if(info.access_type === 'HTTP') {
          params.request_info.method = info.method;
          params.request_info.url = info.url
        } else {
          params.request_info.endpoint = info.endpoint;
          params.request_info.model_name = info.model_name;
          params.request_info.token = info.token;
        }
        if(type === 'add') {
          await api.createApi({
            body: params
          })
        } else {
          await api.updateApi({
            body: {
              ...params,
              id: record.id
            }
          })
        }
        closeDialog && closeDialog();
        getList && getList();
      })
      .catch(err => {
        console.log('err: ', err);
      })
      .finally(() => {

      })
  }
  const title = actionType[type] + 'API';
  return <Drawer
    visible={visible}
    title={title}
    closable={false}
    width={650}
    footer={
      <>
        <Button style={{ float: 'right', marginLeft: '12px' }} type='primary' onClick={onOk}>确定</Button>
        <Button style={{ float: 'right' }} onClick={closeDialog}>取消</Button>
      </>
    }
    onClose={closeDialog}
  >
    <Form
      form={form}
      {...layout} initialValues={{
        access_type: 'EAS',
        method: 'post'
      }}>
      <Form.Item name='name' label='API名称' rules={[{ required: true, message: '请输入API名称' }]}>
        <Input disabled={disabled} placeholder='请输入API名称' />
      </Form.Item>
      <Form.Item name='type' label='API类型' rules={[{ required: true, message: '请选择API类型' }]}>
        <Select disabled={disabled}>
          {
            apiTypes.map(item => {
              return <Option key={item.key} value={item.key}>{item.name}</Option>
            })
          }
        </Select>
      </Form.Item>
      <Form.Item name='access_type' label='接入方式' rules={[{ required: true, message: '请选择接入方式' }]}>
        <Select disabled={disabled} onChange={(value: string) => setMode(value)}>
          <Option value='EAS'>EAS</Option>
          <Option value='HTTP'>HTTP</Option>
        </Select>
      </Form.Item>
      {
        mode === 'EAS' && <>
          <Form.Item name='model_name' label='modal name' rules={[{ required: true, message: '请输入modal name' }]}>
            <Input disabled={disabled} />
          </Form.Item>
          <Form.Item name='token' label='token' rules={[{ required: true, message: '请输入token' }]}>
            <Input disabled={disabled} />
          </Form.Item>
          <Form.Item name='endpoint' label='endpoint' rules={[{ required: true, message: '请输入endpoint' }]}>
            <Input disabled={disabled} />
          </Form.Item>
        </>
      }
      {
        mode === 'HTTP' && <>
          <Form.Item name='url' label='访问地址' rules={[{ required: true, message: '请输入访问地址' }]}>
            <Input disabled={disabled} />
          </Form.Item>
          <Form.Item name='method' label='访问方式' rules={[{ required: true, message: '请选择访问方式' }]}>
            <Select disabled={disabled}>
              <Option value='get'>GET</Option>
              <Option value='post'>POST</Option>
              <Option value='patch'>PATCH</Option>
              <Option value='put'>PUT</Option>
            </Select>
          </Form.Item>
        </>
      }
      <Form.Item name='desc' label='描述' >
        <Input.TextArea  disabled={disabled}  />
      </Form.Item>
    </Form>
  </Drawer>
}

export default wrapper(CreateApiModal);